package com.bree.erp.service.stateless;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.MasterItem;
import com.bree.erp.entity.PartUnit;
import com.bree.erp.entity.Unit;
import com.bree.erp.service.PartUnitService;

@Stateless
public class PartUnitServiceBean implements PartUnitService {

	@PersistenceContext()
	private EntityManager em;
	
	public PartUnitServiceBean() {
		
	}
	
	public PartUnitServiceBean(EntityManager em) {
		this.em = em;
	}
	
	@Override
	public PartUnit create(Long masterItemId, String unitCode, String partName) {
		
		MasterItem masterItem = em.find(MasterItem.class, masterItemId);
		Unit unit = em.find(Unit.class, unitCode);
		
		return create(masterItem, unit, partName);
	}

	@Override
	public PartUnit create(MasterItem masterItem, Unit unit, String partName) {
		PartUnit partUnit = new PartUnit();
		
		partUnit.setMasterItem(masterItem);
		partUnit.setUnit(unit);
		partUnit.setPart(partName);
		
		em.persist(partUnit);
		
		return partUnit;
	}

	@Override
	public PartUnit read(Long id) {
		return em.find(PartUnit.class, id);
	}

	@Override
	public PartUnit update(Long id, String partName) {

		PartUnit partUnit = read(id);
		
		partUnit.setPart(partName);
		
		return partUnit;
	}

	@Override
	public void delete(Long id) {

		PartUnit partUnit = read(id);
		
		em.remove(partUnit);
		
	}

	@Override
	public Collection<PartUnit> list() {
		
		TypedQuery<PartUnit> query = em.createNamedQuery(PartUnit.QUERY_SELECT_ALL_PARTUNIT, PartUnit.class);
		
		return query.getResultList();
	}

}
